package config

import (
	"log"
	"os"
	"path/filepath"

	"gopkg.in/yaml.v3"
)

const (
	mysqlConfig = "mysql.yaml"
)

type MysqlCnf map[string]MyConf

type MyConf struct {
	Username string `json:"username" yaml:"username"`
	Password string `json:"password" yaml:"password"`
	IP       string `json:"ip" yaml:"ip"`
	Port     int    `json:"port" yaml:"port"`
	Charset  string `json:"charset" yaml:"charset"`
	Dbname   string `json:"dbname" yaml:"dbname"`

	MaxIdleConns    int `json:"max_idle_conns" yaml:"max_idle_conns"`
	MaxOpenConns    int `json:"max_open_conns" yaml:"max_open_conns"`
	ConnMaxLifetime int `json:"conn_max_lifetime" yaml:"conn_max_lifetime"`
	ConnMaxIdleTime int `json:"conn_max_idletime" yaml:"conn_max_idletime"`
}

func (config *MysqlCnf) Init() {
	filePath := filepath.Join(configPath, mysqlConfig)
	content, err := os.ReadFile(filePath)
	if err != nil {
		log.Panicf("load %s error %v", mysqlConfig, err)
	}
	err = yaml.Unmarshal(content, &config)
	if err != nil {
		log.Panicf("unmarshal %s error %v", mysqlConfig, err)
	}
}

func (config MysqlCnf) Conf(key string) MyConf {
	if key == "" {
		log.Panicf("key不能为空")
	}
	if _, ok := config[key]; !ok {
		log.Panicf("不存在%s的配置", key)
	}
	return config[key]
}
